// pages/admin/rescue-manage/rescue-manage.js
const { get, put } = require('../../../utils/request')
const { formatDate, showSuccess, showError, showConfirm } = require('../../../utils/util')

Page({
  data: {
    rescueList: [],
    statusIndex: 0,
    statusList: ['全部状态', '待处理', '处理中', '已完成'],
    loading: false
  },

  onLoad() {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    this.loadRescueList()
  },

  onShow() {
    this.loadRescueList()
  },

  onPullDownRefresh() {
    this.loadRescueList(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 加载救助申请列表
  loadRescueList(callback) {
    this.setData({ loading: true })

    const params = {}

    // 添加状态筛选
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusList[this.data.statusIndex]
    }

    get('/rescue/list', params).then(res => {
      const rescueList = res.data || []
      
      // 格式化时间
      rescueList.forEach(item => {
        item.createTime = formatDate(item.createTime)
        if (item.handleTime) {
          item.handleTime = formatDate(item.handleTime)
        }
      })

      this.setData({
        rescueList
      })
    }).catch(err => {
      showError('加载失败')
    }).finally(() => {
      this.setData({ loading: false })
      callback && callback()
    })
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value)
    })
    this.loadRescueList()
  },

  // 刷新
  onRefresh() {
    this.loadRescueList()
  },

  // 查看详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/rescue-review/rescue-review?id=${id}`
    })
  },

  // 处理救助申请
  async handleRescue(e) {
    const id = e.currentTarget.dataset.id
    const item = this.data.rescueList.find(item => item.id === id)
    
    if (!item) return

    let newStatus, actionText
    if (item.status === '待处理') {
      newStatus = '处理中'
      actionText = '开始处理'
    } else if (item.status === '处理中') {
      newStatus = '已完成'
      actionText = '标记完成'
    } else {
      return
    }

    try {
      await showConfirm(`确定要${actionText}这个救助申请吗？`)
    } catch {
      return
    }

    // 弹出备注输入框
    wx.showModal({
      title: '处理备注',
      content: '',
      placeholderText: '请输入处理备注',
      editable: true,
      success: (res) => {
        if (res.confirm) {
          const handleNote = res.content || `${actionText}于${new Date().toLocaleString()}`
          
          // 使用专门的处理接口，传递查询参数
          const handleUrl = `/rescue/handle/${id}?status=${encodeURIComponent(newStatus)}&handleNote=${encodeURIComponent(handleNote)}`

          put(handleUrl).then(res => {
            showSuccess(`${actionText}成功`)
            this.loadRescueList()
          }).catch(err => {
            showError(err.msg || `${actionText}失败`)
          })
        }
      }
    })
  }
})
